print("Starting Flask application...")

from flask import Flask, render_template
from config import Config
from extensions import db
from sqlalchemy import text
import os

app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)

from models import MyTable

def check_and_create_table():
    with app.app_context():
        inspector = db.inspect(db.engine)
        if not inspector.has_table('my_table'):
            print("Table 'my_table' does not exist. Creating table and inserting data...")
            with db.engine.connect() as connection:
                with connection.begin() as transaction:
                    try:
                        with open(os.path.join(os.path.dirname(__file__), 'ddl_dml.sql'), 'r') as file:
                            sql_commands = file.read().split(';')
                            for command in sql_commands:
                                if command.strip():
                                    print(f"Executing SQL command: {command.strip()}")
                                    connection.execute(text(command))
                        transaction.commit()
                        print("Table 'my_table' created and data inserted.")
                    except Exception as e:
                        transaction.rollback()
                        print(f"Error occurred: {e}")
        else:
            print("Table 'my_table' already exists.")

@app.route('/')
def index():
    data = MyTable.query.all()
    return render_template('index.html', data=data)

if __name__ == '__main__':
    check_and_create_table()
    print("Running Flask development server...")
    app.run(debug=True)
